package com.alameda.service.user;

import com.alameda.mapper.user.UserMapper;
import com.alameda.user.bo.UserBO;
import com.alameda.user.dto.UserDTO;
import com.alameda.user.pojo.UserDO;
import com.alameda.user.vo.UserVO;
import com.alameda.utils.ExcelUtils;
import com.alameda.utils.ObjectUtils;
import com.alameda.utils.PubUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户 业务逻辑层 具体实现扩展
 *
 * @author Lv
 * @date 2024/2/19
 */
@Slf4j
@Service
@Primary
public class UserServiceImplExt extends UserServiceImpl {

    @Autowired
    private UserMapper userMapper;

    /**
     * 查询用户列表
     *
     * @param userDTO 用户数据传递对象
     * @return
     */
    @Override
    public IPage<UserVO> loadUser(UserDTO userDTO) {
        IPage<UserDO> iPage = new Page<>(userDTO.getPageNum(), userDTO.getPageSize());
        return userMapper.listUserData(iPage, userDTO.getNickname(), userDTO.getEmail(), userDTO.getOrganizationId());
    }

    /**
     * 导出excel
     *
     * @param userDTO 用户数据传递对象
     */
    @Override
    public void export(UserDTO userDTO) {
        List<UserBO> userBOList = getExportData(userDTO);
        ExcelUtils.export(userBOList, UserBO.class, "用户信息");
    }

    /**
     * 获取导出数据
     *
     * @param userDTO 用户数据传递对象
     * @return
     */
    private List<UserBO> getExportData(UserDTO userDTO) {
        IPage<UserVO> pageData = loadUser(userDTO);
        List<UserVO> dataList = pageData.getRecords();

        if (PubUtils.isEmpty(userDTO.getIdList())) {
            // 获取当前页面数据
            return ObjectUtils.convertList(dataList, UserBO.class);
        } else {
            // 获取选中数据
            return dataList.stream()
                    .filter(item -> userDTO.getIdList().contains(item.getId()))
                    .map(item -> ObjectUtils.convert(item, UserBO.class))
                    .collect(Collectors.toList());
        }
    }

    /**
     * 删除组织下的用户
     *
     * @param organizationIdList 组织id集合
     * @return
     */
    @Override
    public Boolean removeByOrganizationIdList(List<Long> organizationIdList) {
        return this.remove(Wrappers.lambdaQuery(UserDO.class)
                .in(UserDO::getOrganizationId, organizationIdList));
    }
}
